/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.wh.transaction.receiptfromsupplier;

import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosTransactionBarcode;
import com.ronsicecream.pos.entities.PosTransactionHoPurchaseOrderSupplier;
import com.ronsicecream.pos.entities.PosTransactionHoPurchaseOrderSupplierDetail;
import com.ronsicecream.pos.entities.PosTransactionHoReceiptFromSupplier;
import com.ronsicecream.pos.entities.PosTransactionHoReceiptFromSupplierDetail;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.wh.transaction.receiptfromsupplierdetail.ReceiptFromSupplierDetail;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author user
 */
public class ReceiptFromSupplier extends Page {

    private Field receiptId;
    private Field receiptDate;
    private Field receiptNumber;
    private Field receiptTotal;
    private Field receiptQuantity;
    private Field receiptPaid;
    private Field receiptUnpaid;
    private Field receiptKeel;
    private Field receiptDescription;
    private Field receiptTimestamp;
    private Field receiptPurchaseOrderId;
    private Field receiptSupplierId;
    private Field receiptRegionalId;
    private Field receiptUserId;
    private Field receiptUnitId;
    private Action actionPrintBarcode = new Action("printBarcode", "Print Barcode");
    private Action actionPrintAllBarcode = new Action("printAllBarcode", "Print All Barcode");
    private Action actionPrintMultipleBarcode = new Action("printMultipleBarcode", "Print Multiple Barcode");

    public ReceiptFromSupplier() {
        super();

        setTheClass(PosTransactionHoReceiptFromSupplier.class);
        setPageDetail(ReceiptFromSupplierDetail.class);

        receiptId = new Field();
        receiptId.setName("receiptId");
        receiptId.setCaption("id");
        receiptId.setListProperties("");
        receiptId.setInputProperties("");
        getFields().add(receiptId);

        receiptNumber = new Field();
        receiptNumber.setName("receiptNumber");
        receiptNumber.setCaption("number");
        receiptNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        receiptNumber.setInputProperties(" size=\"30\" readonly");
        receiptNumber.setRequired(true);
        getFields().add(receiptNumber);

        receiptUnitId = new Field();
        receiptUnitId.setName("receiptUnitId");
        receiptUnitId.setCaption("unit");
        receiptUnitId.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        receiptUnitId.setInputProperties("");
        getFields().add(receiptUnitId);

        receiptSupplierId = new Field();
        receiptSupplierId.setName("receiptSupplierId");
        receiptSupplierId.setCaption("supplier");
        receiptSupplierId.setListProperties(" width=\"10%\" nowrap");
        receiptSupplierId.setInputProperties(" size=\"30\" ");
        receiptSupplierId.setRequired(true);
        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierCode", " Code", "width=\"30%\" nowrap"});
        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierName", " Name", "width=\"50%\""});
        receiptSupplierId.getSelectorColumns().add(new String[]{"supplierPhone", " Phone", "align=\"center\" width=\"20%\" nowrap"});
        getFields().add(receiptSupplierId);

        receiptRegionalId = new Field();
        receiptRegionalId.setName("receiptRegionalId");
        receiptRegionalId.setCaption("regional");
        receiptRegionalId.setListProperties(" width=\"10%\" nowrap");
        receiptRegionalId.setInputProperties(" size=\"30\" ");
        receiptRegionalId.setRequired(true);
        receiptRegionalId.getSelectorColumns().add(new String[]{"regionalCode", " Code", "width=\"30%\" nowrap"});
        receiptRegionalId.getSelectorColumns().add(new String[]{"regionalName", " Name", "width=\"50%\""});
        getFields().add(receiptRegionalId);

        receiptPurchaseOrderId = new Field();
        receiptPurchaseOrderId.setName("receiptPurchaseOrderId");
        receiptPurchaseOrderId.setCaption("purchase order");
        receiptPurchaseOrderId.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        receiptPurchaseOrderId.setInputProperties(" size=\"20\" readonly");
        receiptPurchaseOrderId.setRequired(true);
        receiptPurchaseOrderId.setSelectorLoad(true);
        receiptPurchaseOrderId.setSelectorCondition("t.purchaseOrderUnreceived > 0 AND t.purchaseOrderProgress='4'");
        receiptPurchaseOrderId.getSelectorAction().add(new String[]{"value", "receiptSupplierId", "purchaseOrderSupplierId"});
//        receiptPurchaseOrderId.getSelectorAction().add(new String[]{"value", "receiptPurchaseOrderReceived", "purchaseOrderReceived"});
//        receiptPurchaseOrderId.getSelectorAction().add(new String[]{"value", "receiptDescription", "purchaseOrderDescription"});
        receiptPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderNumber", "Number", "width=\"20%\" nowrap"});
        receiptPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderSupplierId", "Supplier", "width=\"20%\""});
        receiptPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderQuantity", " Total Quantity", " align=\"right\" width=\"10%\" nowrap"});
        receiptPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderReceived", " Received", " align=\"right\" width=\"10%\" nowrap"});
        receiptPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderDescription", " Description", "width=\"40%\""});
        receiptPurchaseOrderId.setSelectorOrder("t.purchaseOrderNumber");
        getFields().add(receiptPurchaseOrderId);

        receiptQuantity = new Field();
        receiptQuantity.setName("receiptQuantity");
        receiptQuantity.setCaption("total quantity");
        receiptQuantity.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptQuantity.setInputProperties(" size=\"8\" readonly");
        getFields().add(receiptQuantity);

        receiptDate = new Field();
        receiptDate.setName("receiptDate");
        receiptDate.setCaption("date");
        receiptDate.setListProperties(" align=\"center\" width=\"6%\" nowrap");
        receiptDate.setInputProperties(" size=\"8\" readonly");
        receiptDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(receiptDate);

        receiptTotal = new Field();
        receiptTotal.setName("receiptTotal");
        receiptTotal.setCaption("total");
        receiptTotal.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptTotal.setInputProperties(" size=\"8\"");
        receiptTotal.setRequired(true);
//        receiptTotal.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptTotal);

        receiptPaid = new Field();
        receiptPaid.setName("receiptPaid");
        receiptPaid.setCaption("paid");
        receiptPaid.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptPaid.setInputProperties(" size=\"8\"");
        receiptPaid.setRequired(true);
//        receiptPaid.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptPaid);

        receiptUnpaid = new Field();
        receiptUnpaid.setName("receiptUnpaid");
        receiptUnpaid.setCaption("unpaid");
        receiptUnpaid.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        receiptUnpaid.setInputProperties(" size=\"8\"");
        receiptUnpaid.setRequired(true);
//        receiptPaid.setFormater(MoneyFormatter.getInstance());
        getFields().add(receiptUnpaid);

        receiptKeel = new Field();
        receiptKeel.setName("receiptKeel");
        receiptKeel.setCaption("keel");
        receiptKeel.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        receiptKeel.setInputProperties(" ");
        receiptKeel.getOptions().add(new String[]{"1", "NO"});
        receiptKeel.getOptions().add(new String[]{"2", "YES"});
        getFields().add(receiptKeel);

        receiptTimestamp = new Field();
        receiptTimestamp.setName("receiptTimestamp");
        receiptTimestamp.setCaption("timestamp");
        receiptTimestamp.setListProperties(" align=\"center\" width=\"1%\" nowrap");
        receiptTimestamp.setInputProperties(" size=\"12\"");
        getFields().add(receiptTimestamp);

        receiptDescription = new Field();
        receiptDescription.setName("receiptDescription");
        receiptDescription.setCaption("description");
        receiptDescription.setListProperties(" width=\"70%\"");
        receiptDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        receiptDescription.setInputType(Field.INPUT_TEXT_AREA);
        receiptDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(receiptDescription);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(receiptNumber);
        getFieldsAdd().add(receiptPurchaseOrderId);
        getFieldsAdd().add(receiptDate);
        getFieldsAdd().add(receiptDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(receiptNumber);
        getFieldsEdit().add(receiptPurchaseOrderId);
        getFieldsEdit().add(receiptDate);
        getFieldsEdit().add(receiptDescription);

        getFieldsList().clear();
        getFieldsList().add(receiptNumber);
        getFieldsList().add(receiptPurchaseOrderId);
        getFieldsList().add(receiptSupplierId);
        getFieldsList().add(receiptDate);
        getFieldsList().add(receiptQuantity);
        getFieldsList().add(receiptTotal);
        getFieldsList().add(receiptPaid);
        getFieldsList().add(receiptUnpaid);
        getFieldsList().add(receiptKeel);
        getFieldsList().add(receiptDescription);

        getFieldsView().clear();
        getFieldsView().add(receiptDate);
        getFieldsView().add(receiptNumber);
        getFieldsView().add(receiptQuantity);
        getFieldsView().add(receiptSupplierId);
        getFieldsView().add(receiptTotal);
        getFieldsView().add(receiptPaid);
        getFieldsView().add(receiptUnpaid);
        getFieldsView().add(receiptKeel);
        getFieldsView().add(receiptDescription);
        getFieldsView().add(receiptPurchaseOrderId);
        getFieldsView().add(receiptTimestamp);

        setExportList(getClass().getResourceAsStream("ReceiptList.jasper"));
        setExport(getClass().getResourceAsStream("Receipt.jasper"));

        setController(new ReceiptFromSupplier.ReceiptFromSupplierController(this));
        getController().setOrder(receiptTimestamp);
        getController().setOrderType(Controller.ORDER_DESC);



    }

    @Override
    public void beforeList() {
        if (!getCurrentUnit().getUnitId().equals(1)) {
            getController().setCondition("t.receiptUnitId.unitId=" + getCurrentUnit().getUnitId());
        }
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        receiptDate.setFormater(DateFormatter.getInstanceDate(this));
        receiptTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        receiptNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionHoReceiptFromSupplier rec = (PosTransactionHoReceiptFromSupplier) getEntityManager().createQuery("SELECT t FROM PosTransactionHoReceiptFromSupplier t "
                    + "WHERE t.receiptNumber LIKE '%/" + unitCode + "/Rons/REC-Supplier/%/" + year + "' "
                    + "ORDER BY t.receiptTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getReceiptNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/REC-Supplier/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/REC-Supplier/" + month + "/" + year;
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintBarcode)) {
            command = new StringBuffer(template.toString());
            String encodedId = Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField()));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintBarcode.getName() + "&id=" + encodedId);
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Barcode"));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printBarcode('" + encodedId + "')\"");
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/bullet-barcode.png");
            commands.append(command.toString());
            commands.append("<input type=\"text\" class=\"form-text\" name=\"barcode_quantity_" + encodedId + "\" value=\"1\" style=\"width: 20px; margin: 0 5px; text-align: right; font-size: 8px;\">");
        }
        return commands;
    }

    @Override
    public StringBuffer processCustomCommand(StringBuffer template, Page page) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintMultipleBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Multiple Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printMultipleBarcode('" + "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName() + "', 'form-" + page.getMenu().getMenuName() + "')\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode.png");
            commands.append(command.toString());
        }
        if (Access.isGranted(page, actionPrintAllBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintAllBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print All Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printAllBarcode()\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode-all.png");
            commands.append(command.toString());
        }
        return commands;
    }

    @Override
    public String doAction() {
        if (getAction().equals(actionPrintBarcode)) {
            String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
            PosTransactionHoReceiptFromSupplierDetail itemBarcode = (PosTransactionHoReceiptFromSupplierDetail) getController().getData(id);
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            PosTransactionBarcode barcode = new PosTransactionBarcode();
            barcode.setBarcodeId(Sequence.next(barcode));
            barcode.setBarcodeBarcode(itemBarcode.getReceiptDetailBarcode());
            barcode.setBarcodeInformation("Exp " + itemBarcode.getReceiptDetailDateExpired().toString());
            em.persist(barcode);
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintMultipleBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                String[] ids = Utility.getPostParameterValues(this, "uniqId");
                for (String id : ids) {
                    PosTransactionHoReceiptFromSupplierDetail itemBarcode = (PosTransactionHoReceiptFromSupplierDetail) getController().getData(Utility.decode(id));
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(itemBarcode.getReceiptDetailBarcode());
                    barcode.setBarcodeInformation("Exp " + itemBarcode.getReceiptDetailDateExpired().toString());
                    try {
                        barcode.setBarcodeQuantity(Integer.parseInt(Utility.getPostParameterEmpty(this, "barcode_quantity_" + id)));
                    } catch (Exception e) {
                    }
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintAllBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                List<PosTransactionHoReceiptFromSupplierDetail> itemBarcode = em.createQuery("SELECT t FROM PosTransactionHoReceiptFromSupplierDetail t").setHint(Persistence.REFRESH_HINT, true).getResultList();
                for (PosTransactionHoReceiptFromSupplierDetail barcodes : itemBarcode) {
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(barcodes.getReceiptDetailBarcode());
                    barcode.setBarcodeInformation("Exp " + barcodes.getReceiptDetailDateExpired().toString());
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();
        }
        setEditActionRedirect("m=" + getMenu().getMenuName() + "&a=" + Action.EDIT.getName() + "&id=" + Utility.decode(Utility.getPostParameter(this, "id")));
        return super.doAction();
    }

    class ReceiptFromSupplierController extends Controller {

        public ReceiptFromSupplierController(Page page) {
            super(page);
            setOrder("receiptTimestamp");
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List list) {
            PosTransactionHoReceiptFromSupplier receipt = (PosTransactionHoReceiptFromSupplier) data;
            EntityManager em = getEntityManager();
            receipt.setReceiptNumber(generate());
            receipt.setReceiptUnitId(getCurrentUnit());
            receipt.setReceiptUserId(getCurrentUser());
            receipt.setReceiptTimestamp(Utility.getTimestamp());
            receipt.setReceiptDate(Utility.getFirstDate());
            receipt.setReceiptKeel("1");
            receipt.setReceiptPaid(BigDecimal.ZERO);
            System.out.println(" Jalan ga ");
            for (Object detail : list) {
                System.out.println(" Jalan ga jos ");
                PosTransactionHoReceiptFromSupplierDetail receiptDetail = (PosTransactionHoReceiptFromSupplierDetail) detail;
                DateFormat df = new SimpleDateFormat("ddMMyyyy HH:mm:ss");
                long today = receiptDetail.getReceiptDetailDateExpired().getTime();
                String reportDate = df.format(today);
                System.out.println("Report Date: " + reportDate.substring(0, 4));
                System.out.println("Report Date dua: " + reportDate.substring(6, 8));
                receiptDetail.setReceiptDetailBarcode(reportDate.substring(0, 4) + reportDate.substring(6, 8) + generateBarcode());
                System.out.println(" jalan ga " + receiptDetail.getReceiptDetailBarcode());
            }
        }

        @Override
        public void afterInsert(Object data, List list) {

            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionHoReceiptFromSupplier receipt = (PosTransactionHoReceiptFromSupplier) data;
                PosTransactionHoPurchaseOrderSupplier po = receipt.getReceiptPurchaseOrderId();

                receipt.setReceiptSupplierId(po.getPurchaseOrderSupplierId());
                receipt.setReceiptRegionalId(po.getPurchaseOrderRegionalId());
                System.out.println("receipt regional :" + receipt.getReceiptRegionalId() + " po regional :" + po.getPurchaseOrderRegionalId());
                receipt.setReceiptPosUnitId(po.getPurchaseOrderPosUnitId());
                System.out.println(" supplier ya disini :" + receipt.getReceiptSupplierId() + " posUnit :" + receipt.getReceiptPosUnitId());
//                receipt.setReceiptRegionalId(po.getPurchaseOrderRegionalId());
//                System.out.println(" regional ya disini :"+receipt.getReceiptRegionalId());

                BigDecimal total = BigDecimal.ZERO;
                BigDecimal totalQuantity = BigDecimal.ZERO;
                for (Object detail : list) {
                    PosTransactionHoReceiptFromSupplierDetail receiptDetail = (PosTransactionHoReceiptFromSupplierDetail) detail;

                    PosTransactionHoPurchaseOrderSupplierDetail poDetail = (PosTransactionHoPurchaseOrderSupplierDetail) em.createQuery("SELECT t FROM PosTransactionHoPurchaseOrderSupplierDetail t"
                            + " WHERE t.purchaseOrderDetailItemId.itemId=" + receiptDetail.getReceiptDetailItemId().getItemId()
                            //                            + " AND t.purchaseOrderDetailSatuanId.satuanId="+receiptDetail.getReceiptDetailSatuanId().getSatuanId()
                            + " AND t.purchaseOrderDetailPurchaseOrderId.purchaseOrderId=" + po.getPurchaseOrderId())
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    System.out.println(" poDetail ya disini :" + poDetail + " >>po:" + po.getPurchaseOrderId());
                    poDetail.setPurchaseOrderDetailSent(poDetail.getPurchaseOrderDetailSent().add(receiptDetail.getReceiptDetailQuantity()));
                    poDetail.setPurchaseOrderDetailUnsent(poDetail.getPurchaseOrderDetailUnsent().subtract(receiptDetail.getReceiptDetailQuantity()));

                    PosMasterItemStock stock = Item.getStockItem(em, receiptDetail.getReceiptDetailItemId(), receipt.getReceiptUnitId());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();

                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(receiptDetail.getReceiptDetailItemId());
                    itemStock.setItemStockUnitId(receipt.getReceiptUnitId());
                    itemStock.setItemStockStatusId(statusGood);
                    itemStock.setItemStockType("1");
                    itemStock.setItemStockRegionalId(receipt.getReceiptRegionalId());
                    itemStock.setItemStockPosUnitId(receipt.getReceiptPosUnitId());
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockValue(receiptDetail.getReceiptDetailQuantity());
                    itemStock.setItemStockCurrent(stock.getItemStockValue().add(itemStock.getItemStockValue()));
                    itemStock.setItemStockUserId(getCurrentUser());
                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    System.out.println(itemStock.getItemStockId() + "<<=========dedy=" + itemStock.getItemStockRegionalId());
                    em.persist(itemStock);

                    stock.setItemStockValue(itemStock.getItemStockCurrent());
                    stock.setItemStockTimestamp(Utility.getTimestamp());


                    total = total.add(receiptDetail.getReceiptDetailPrice().multiply(receiptDetail.getReceiptDetailQuantity()));
                    totalQuantity = totalQuantity.add(receiptDetail.getReceiptDetailQuantity());
                }
                System.out.println(" Totalnya disini :" + total);
                System.out.println(" Quantitynya disini :" + totalQuantity);
                receipt.setReceiptTotal(total);
                receipt.setReceiptQuantity(totalQuantity);
                receipt.setReceiptUnpaid(total);

                po.setPurchaseOrderUnreceived(po.getPurchaseOrderUnreceived().subtract(totalQuantity));
                po.setPurchaseOrderReceived(po.getPurchaseOrderReceived().add(totalQuantity));
                System.out.println(" Tessss ");
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println(" Erorrnya disini :" + e);
            }
        }

        private String generateBarcode() {

            Random random = new Random();
            String bcode = "" + (random.nextInt(899999) + 100000);
            System.out.println("jose barcode" + bcode);
            String barcode;
            if (bcode.length() == 1) {
                barcode = "00000" + bcode;
            } else if (bcode.length() == 2) {
                barcode = "0000" + bcode;
            } else if (bcode.length() == 3) {
                barcode = "000" + bcode;
            } else if (bcode.length() == 4) {
                barcode = "00" + bcode;
            } else if (bcode.length() == 5) {
                barcode = "0" + bcode;
            } else {
                barcode = bcode;
            }
            return barcode;
        }

        private String cekBarcode() {
            EntityManager em = getEntityManager();
            String barcode = generateBarcode();
            try {
                Query query = em.createQuery("SELECT t PosTransactionHoReceiptFromSupplierDetail t WHERE t.receiptDetailBarcode =" + generateBarcode());
                List<PosTransactionHoReceiptFromSupplierDetail> list = query.getResultList();
                System.out.println("" + list);
                if (list.size() > 0) {
                    exist();
                } else if ("0000000000".equals(barcode)) {
                    exist();
                } else {
                    return barcode;
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            return barcode;
        }

        public void exist() {
            cekBarcode();
        }
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Receipt From Supplier"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
